#include "xThread.h"

namespace xNet
{
    xThread::xThread()
            : m_bDetach(false)
            , m_bJoin(true)
            , m_bStart(true)
            , m_bTermnation(false)
            , m_state(THREAD_STATE_NOT_INIT)
    {
    }

    xThread::~xThread()
    {

    }

    void* xThread::ThreadFunc(void* arg)
    {
        xThread* xth = static_cast<xThread*>(arg);
        xth->Run();
        return nullptr;
    }

    void xThread::Start()
    {
        pthread_attr_t att;
        pthread_attr_init(&att);
        if(m_bDetach) 
        {
            pthread_attr_setdetachstate(&att,PTHREAD_CREATE_DETACHED);
            m_bDetach = true;
            m_bJoin = false;
        }
        if(pthread_create(&m_pthreadId, &att, ThreadFunc, this)!=0)
        {
            return ;
        }
        pthread_attr_destroy(&att);
        SetState(THREAD_STATE_RUNNING);
    }

    void xThread::Finish()
    {
        SetTermnation(true);
        if(m_bJoin)
        {
            Join();
        }
        SetState(THREAD_STATE_EXIT);
    }

    void xThread::Join()
    {
        if(!m_bDetach && m_bJoin)
        {
            pthread_join(m_pthreadId,NULL);
        }
    }

    xThreadContainer::xThreadContainer(uint32 defaultSize)
    {
    }

    void xThreadContainer::AddThread(xThread* th)
    {
        m_threads.push_back(th);
    }

    xThread* xThreadContainer::GetThread(uint32 dwIndex)
    {
        if(m_threads.size() <= dwIndex)
        {
            return nullptr;
        }
        return m_threads[dwIndex];
    }

    void xThreadContainer::Finish()
    {
        for(uint32 i=0;i<m_threads.size();++i)
        {
            xThread* th = m_threads[i];
            th->Finish();
            DELETE(th);
        }
        m_threads.clear();
    }
}